<?php
namespace app\api\controller;

use app\api\model\Activity as ActivityModel;
use think\Request;
use think\Db;
use think\Exception;

/**
 * 活动API控制器
 * Class Activity
 * @package app\api\controller
 */
class Activity extends BaseController
{
    /**
     * 获取活动列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function getList(Request $request)
    {
        // 获取请求参数
        $page = $request->param('page', 1);
        $limit = $request->param('limit', 10);
        $type = $request->param('type', ''); // 活动类型
        $status = $request->param('status', 'active'); // active进行中, upcoming即将开始, ended已结束
        
        try {
            // 查询条件
            $where = ['status' => 1];
            
            // 如果指定了活动类型，则按类型筛选
            if (!empty($type)) {
                $where['type'] = $type;
            }
            
            // 根据状态筛选
            $now = time();
            switch ($status) {
                case 'active':
                    $where['start_time'] = ['<=', $now];
                    $where['end_time'] = ['>=', $now];
                    break;
                case 'upcoming':
                    $where['start_time'] = ['>', $now];
                    break;
                case 'ended':
                    $where['end_time'] = ['<', $now];
                    break;
            }
            
            // 查询活动列表
            $activities = ActivityModel::where($where)
                ->field('id, title, image, type, start_time, end_time, location, content, participant_count, max_participants')
                ->order(['sort' => 'asc', 'id' => 'desc'])
                ->paginate($limit, false, ['page' => $page]);
                
            // 处理数据
            $list = $activities->items();
            foreach ($list as &$item) {
                $item['start_time_text'] = date('Y-m-d H:i', $item['start_time']);
                $item['end_time_text'] = date('Y-m-d H:i', $item['end_time']);
                
                // 活动状态
                if ($item['start_time'] > time()) {
                    $item['status'] = 'not_started';
                    $item['status_text'] = '未开始';
                } else if ($item['end_time'] < time()) {
                    $item['status'] = 'ended';
                    $item['status_text'] = '已结束';
                } else {
                    $item['status'] = 'in_progress';
                    $item['status_text'] = '进行中';
                }
            }
            
            $result = [
                'data' => $list,
                'total' => $activities->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $activities->lastPage()
            ];
            
            return $this->renderSuccess('获取成功', $result);
        } catch (Exception $e) {
            return $this->renderError('获取活动列表失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取活动详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function detail(Request $request)
    {
        // 获取请求参数
        $id = $request->param('id');
        
        if (empty($id)) {
            return $this->renderError('参数错误：缺少活动ID');
        }
        
        try {
            // 查询活动详情
            $detail = ActivityModel::where([
                'id' => $id,
                'status' => 1
            ])->find();
            
            if (!$detail) {
                return $this->renderError('活动不存在或已下线');
            }
            
            // 处理数据
            $detail['start_time_text'] = date('Y-m-d H:i', $detail['start_time']);
            $detail['end_time_text'] = date('Y-m-d H:i', $detail['end_time']);
            
            // 活动状态
            if ($detail['start_time'] > time()) {
                $detail['status'] = 'not_started';
                $detail['status_text'] = '未开始';
            } else if ($detail['end_time'] < time()) {
                $detail['status'] = 'ended';
                $detail['status_text'] = '已结束';
            } else {
                $detail['status'] = 'in_progress';
                $detail['status_text'] = '进行中';
            }
            
            // 检查用户是否已参与
            $is_participated = false;
            $member_id = $this->getUserId();
            if ($member_id) {
                $participation = Db::name('activity_participants')
                    ->where([
                        'activity_id' => $id,
                        'member_id' => $member_id
                    ])
                    ->find();
                $is_participated = !empty($participation);
            }
            
            $detail['is_participated'] = $is_participated;
            
            // 增加浏览次数
            ActivityModel::where('id', $id)->setInc('view_count');
            
            return $this->renderSuccess('获取成功', $detail);
        } catch (Exception $e) {
            return $this->renderError('获取活动详情失败：' . $e->getMessage());
        }
    }
    
    /**
     * 参与活动
     */
    public function participate()
    {
        $this->checkToken();
        
        $activity_id = input('activity_id/d', 0);
        $member_id = $this->getUserId();
        
        if (!$activity_id) {
            return $this->renderError('活动ID不能为空');
        }
        
        try {
            // 检查活动是否存在且有效
            $activity = ActivityModel::where(['id' => $activity_id, 'status' => 1])->find();
            
            if (!$activity) {
                return $this->renderError('活动不存在');
            }
            
            // 检查活动是否在进行中
            $now = time();
            if ($activity['start_time'] > $now) {
                return $this->renderError('活动尚未开始');
            }
            if ($activity['end_time'] < $now) {
                return $this->renderError('活动已结束');
            }
            
            // 检查是否已参与
            $existing = Db::name('activity_participants')
                ->where([
                    'activity_id' => $activity_id,
                    'member_id' => $member_id
                ])
                ->find();
            
            if ($existing) {
                return $this->renderError('您已参与过此活动');
            }
            
            // 检查参与人数限制
            if ($activity['max_participants'] > 0 && $activity['participant_count'] >= $activity['max_participants']) {
                return $this->renderError('活动参与人数已满');
            }
            
            Db::startTrans();
            try {
                // 添加参与记录
                Db::name('activity_participants')->insert([
                    'activity_id' => $activity_id,
                    'member_id' => $member_id,
                    'participate_time' => date('Y-m-d H:i:s'),
                    'status' => 1
                ]);
                
                // 更新参与人数
                ActivityModel::where('id', $activity_id)->setInc('participant_count');
                
                Db::commit();
                return $this->renderSuccess('参与成功');
            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (Exception $e) {
            return $this->renderError('参与活动失败：' . $e->getMessage());
        }
    }
    
    /**
     * 取消参与活动
     */
    public function cancelParticipation()
    {
        $this->checkToken();
        
        $activity_id = input('activity_id/d', 0);
        $member_id = $this->getUserId();
        
        if (!$activity_id) {
            return $this->renderError('活动ID不能为空');
        }
        
        try {
            // 检查参与记录是否存在
            $participation = Db::name('activity_participants')
                ->where([
                    'activity_id' => $activity_id,
                    'member_id' => $member_id
                ])
                ->find();
            
            if (!$participation) {
                return $this->renderError('您未参与此活动');
            }
            
            // 检查活动是否允许取消参与
            $activity = ActivityModel::where('id', $activity_id)->find();
            
            if ($activity['start_time'] <= time()) {
                return $this->renderError('活动已开始，无法取消参与');
            }
            
            Db::startTrans();
            try {
                // 删除参与记录
                Db::name('activity_participants')
                    ->where([
                        'activity_id' => $activity_id,
                        'member_id' => $member_id
                    ])
                    ->delete();
                
                // 减少参与人数
                ActivityModel::where('id', $activity_id)->setDec('participant_count');
                
                Db::commit();
                return $this->renderSuccess('取消参与成功');
            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }
        } catch (Exception $e) {
            return $this->renderError('取消参与失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取我参与的活动
     */
    public function myActivities()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        try {
            $activities = Db::name('activity_participants')
                ->alias('ap')
                ->join('activities a', 'ap.activity_id = a.id')
                ->where('ap.member_id', $member_id)
                ->field('a.id, a.title, a.image, a.start_time, a.end_time, a.type, ap.participate_time')
                ->order('ap.participate_time desc')
                ->paginate($limit, false, ['page' => $page]);
            
            $result = [
                'data' => $activities->items(),
                'total' => $activities->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $activities->lastPage()
            ];
            
            return $this->renderSuccess('获取成功', $result);
        } catch (Exception $e) {
            return $this->renderError('获取我的活动失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取活动参与者列表
     */
    public function getParticipants()
    {
        $activity_id = input('activity_id/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 20);
        
        if (!$activity_id) {
            return $this->renderError('活动ID不能为空');
        }
        
        try {
            $participants = Db::name('activity_participants')
                ->alias('ap')
                ->join('members m', 'ap.member_id = m.member_id')
                ->where('ap.activity_id', $activity_id)
                ->field('m.member_id, m.nickname, m.avatar, ap.participate_time')
                ->order('ap.participate_time desc')
                ->paginate($limit, false, ['page' => $page]);
            
            $result = [
                'data' => $participants->items(),
                'total' => $participants->total(),
                'page' => $page,
                'limit' => $limit,
                'pages' => $participants->lastPage()
            ];
            
            return $this->renderSuccess('获取成功', $result);
        } catch (Exception $e) {
            return $this->renderError('获取参与者列表失败：' . $e->getMessage());
        }
    }
}